<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/11/2
 * Time: 8:41
 */

namespace app\api\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\config;
use think\Db;

class BaiduTs extends Command
{

    protected function configure()
    {
        $this->setName('baiduts')              		//定义命令的名字
        ->setDescription('baiduts html')      //定义命令的描述
        ->addArgument('method')                   //参数1
        ->addArgument('url')                   //文章url
        ->addArgument('id');                    //文章id
    }

    //php think baiduts articlebingindexnow(publish)
    protected function execute(Input $input, Output $output)
    {

        ini_set('max_execution_time', 600);//秒为单位，自己根据需要定义

        $method = $input->getArgument('method');
        if($method == 'articlebingindexnow'){
            $this->articlebingindexnow();
        }
    }

    private function articlebingindexnow(){
        $this->ticheck();
        $model = Model('app\common\model\Article');
        $limit = 1;
        $sleep = rand(0,2290);

        echo "睡眠".$sleep."秒\r\n";
//        sleep($sleep);
        $contentRs = $model->where(['is_bing_indexnow'=>1,'status'=>1])->order('id asc')->limit($limit)->select();
        echo $model->getLastSql();
//        exit;
        if(!empty($contentRs)){
            $urlArr = [];
            foreach($contentRs as $k=>$v){
                $urlArr[] = $v['url'];
            }
            print_r($urlArr);
//            exit;
            $indexnowRs = $this->submit_bing_indexnow($urlArr,'www.cat-guide.com','160c22b631f549afbd3668f64076b6e0','https://www.cat-guide.com/160c22b631f549afbd3668f64076b6e0.txt');
            if($indexnowRs == 200){
                foreach($contentRs as $k=>$v){
                    $model->where(['id'=>$v['id']])->update(['is_bing_indexnow'=>2]);
                }
            }
            print_r("indexnow:推送结果".$indexnowRs);
        }
    }







    private function ticheck(){
        $nowH = (int)date("H",time());
        if($nowH < 8 || $nowH > 18){
            echo "不在提交时间内！";exit;
        }
    }



    /**
     * pc百度提交
     * @param $url
     * @return mixed
     */
    private function ts($url){
//        echo $url;exit;
//        $urls = array(
//            'http://www.example.com/1.html',
//            'http://www.example.com/2.html',
//        );
        $urls = [$url];
        $api = 'http://data.zz.baidu.com/urls?site=https://www.96919.net&token=n3FdLtt1wjhMghP6';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        echo $url."\r\n";
        print_r($result);
        return json_decode($result,true);
    }


  /************************************下面是m站提交百度推送*********************************************************/
    /**
     * m站百度提交
     * @param $url
     * @return mixed
     */
    private function m_ts($url){
        //        echo $url;exit;
//        $urls = array(
//            'http://www.example.com/1.html',
//            'http://www.example.com/2.html',
//        );
        $urls = [$url];
        $api = 'http://data.zz.baidu.com/urls?site=https://m.96919.net&token=n3FdLtt1wjhMghP6';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        echo $url."\r\n";
        print_r($result);
        return json_decode($result,true);
    }


    private function submit_bing($url_list,$siteUrl) {
        $api_key = '0b6b4e15ea344573a9800a1c1d6c1830';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://ssl.bing.com//webmaster/api.svc/json/SubmitUrlbatch?apikey={$api_key}");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'siteUrl' => $siteUrl,
            'urlList' => $url_list
        ]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Host: ssl.bing.com',
            'Content-Type: application/json; charset=utf-8'
        ]);
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
//        var_dump($response);
//        var_dump($http_code);
        $return = ['code'=>0,'msg'=>'初始化！'];
        if ($http_code == 200 && json_decode($response)->d == null) {
//            echo "推送成功:\r\n";
            $return['code'] = 1;
            $return['msg'] = '推送成功！';
//            foreach ($url_list as $url) {
//                echo $url . "\n";
//            }
        } else {

            echo "推送失败:推送配额不足，https://www.bing.com/webmasters/submiturl\r\n";
            $return['code'] = 2;
            $return['msg'] = '推送失败！';
        }
        return $return;
    }


    private function submit_bing_indexnow($params,$host,$key,$keyLocation)
    {
        $post_params = json_encode([
            'host' => $host,
            'key' => $key,
            'keyLocation' => $keyLocation,
            'urlList' => $params
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => 'https://www.bing.com/indexnow',
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_POSTFIELDS => str_replace('\n', '', $post_params),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json; charset=utf-8',
            ),
        );

        curl_setopt_array($ch, $options);
        curl_exec($ch);
        $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
//        var_dump($result);exit;
        return $result;
    }


}